package com.zzt.upload;

import com.baidu.ueditor.ActionEnter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UeditorController {
    private static final Log log = LogFactory.getLog(UeditorController.class);
    @RequestMapping("/config")
    public void config(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, JSONException {
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            ActionEnter actionEnter = new ActionEnter(request, rootPath);
            String exec=actionEnter.exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/uploadImage")
    @ResponseBody
    public Map<String,Object> uploadImage(HttpServletRequest request,@RequestParam("upfile") MultipartFile file){
        Map<String,Object> map = new HashMap<>();
        //封装的图片上传方法
        String path = request.getSession().getServletContext().getRealPath("/");
        map.put("url", UploadFile.uploadSaveImage(file,path));//上传的图片路径
        map.put("state", "SUCCESS");
        map.put("title", file.getOriginalFilename());
        map.put("original", file.getOriginalFilename());
        return map;
    }

    @RequestMapping("/uploadVideo")
    @ResponseBody
    public Map<String,Object> uploadVideo(HttpServletRequest request,@RequestParam("upfile") MultipartFile file){
        Map<String,Object> map = new HashMap<>();
        String path = request.getSession().getServletContext().getRealPath("/");
        //获取保存视频路径和保存视频第一帧图片路径
        Map<String,Object> videoImage = UploadFile.uploadSaveVideo(file,path);
        map.put("url",videoImage.get("videoPath"));
        map.put("imageUrl",videoImage.get("videoImage"));
        map.put("state", "SUCCESS");
        map.put("title", file.getOriginalFilename());
        map.put("original", file.getOriginalFilename());
        return map;
    }


}
